今天讓我們來稍微把程式碼改為稍作優化和修改,修改的部分主要有以下兩點:
document.getElementById()
改為使用更彈性的 document.querySelector()
,讓後續維護和修改時只需要針對 CSS Selector 去更改就好。Function
改為 Arrow Function
,採用更簡潔且現代流行的寫法。原來 index.js
內的程式碼:
const modal = document.getElementById("projectModal");
const modalTitle = document.getElementById("modalTitle");
const modalDescription = document.getElementById("modalDescription");
const modalTags = document.getElementById("modalTags");
const modalCategories = document.getElementById("modalCategories");
function showProjectDetails(projectId) {
const projectDetails = getProjectDetails(projectId);
modalTitle.textContent = projectDetails.title;
modalDescription.textContent = projectDetails.description;
modalTags.textContent = projectDetails.tags;
modalCategories.textContent = projectDetails.categories;
modal.style.display = "block";
}
function closeProjectDetails() {
modal.style.display = "none";
}
function getProjectDetails(projectId) {
const projects = {
1: {
title: "Project 1",
description: "詳細描述 Project 1...",
tags: ["HTML", "CSS", "JavaScript"],
categories: ["Web Development"]
},
2: {
title: "Project 2",
description: "詳細描述 Project 2...",
tags: ["Vue", "React", "Angular"],
categories: ["Frontend"]
},
3: {
title: "Project 3",
description: "詳細描述 Project 3...",
tags: ["Node.js", "Golang", "Python"],
categories: ["Backend"]
}
};
return projects[projectId];
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
修改後的 index.js
程式碼:
const modal = document.querySelector("#projectModal");
const modalTitle = document.querySelector("#modalTitle");
const modalDescription = document.querySelector("#modalDescription");
const modalTags = document.querySelector("#modalTags");
const modalCategories = document.querySelector("#modalCategories");
const showProjectDetails = (projectId) => {
const projectDetails = getProjectDetails(projectId);
modalTitle.textContent = projectDetails.title;
modalDescription.textContent = projectDetails.description;
modalTags.textContent = projectDetails.tags;
modalCategories.textContent = projectDetails.categories;
modal.style.display = "block";
}
const closeProjectDetails = () => {
modal.style.display = "none";
}
const getProjectDetails = (projectId) => {
const projects = {
1: {
title: "Project 1",
description: "詳細描述 Project 1...",
tags: ["HTML", "CSS", "JavaScript"],
categories: ["Web Development"]
},
2: {
title: "Project 2",
description: "詳細描述 Project 2...",
tags: ["Vue", "React", "Angular"],
categories: ["Frontend"]
},
3: {
title: "Project 3",
description: "詳細描述 Project 3...",
tags: ["Node.js", "Golang", "Python"],
categories: ["Backend"]
}
};
return projects[projectId];
}
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}